<?php
namespace api\controllers;

//use yii\web\Controller;
use common\models\Active;
use common\models\ActiveAttr;
use common\models\Address;
use common\models\Express;
use common\models\MoneyChange;
use common\models\Order;
use common\models\Shop;
use common\models\User;
use common\service\CommonService;
use common\service\ConstantService;
use common\service\GlobalUrlService;
use common\models\Group;
use common\models\Complaint;
use common\service\GoodsService;
use common\service\LogisticsService;
use common\service\RedisServer;

class OrderController extends BaseController
{

    /**
     * 添加订单
     */
    public function actionAddOrder(){
        if($this->isPost()){
            //库存加redis 每次进来根据 goods_id 和goods_attr_id
            $data = $this->post();
            $msg = $this->_validation($data);

            if($msg!== true){
                return $this->renderJson([],$msg,ConstantService::$response_fail);
            }
            //加入redis存储库存
            $key = ConstantService::$redis_key.$data['goods_attr_id'];
            //判断key是否存在，不存在则新增
            $redis = RedisServer::initialization();
            $inventory = $redis->getRedis($key);
            if(!$inventory){
                //没有redis
                $goods_attr = ActiveAttr::findOne(['id'=>$data['goods_attr_id']]);
                $inventory = $goods_attr['inventory'];
            }
            $inventory = $inventory-$data['goods_num'];
            if($inventory<0){
                return $this->renderJson([],'库存不足',ConstantService::$response_fail);
            }
            //设置值
            $redis->addRedis($key,$inventory);

            //先去查该用户和该活动的最后一次参加的团,判断团是否有效 有一个状态值,如果有效则说明该团里面没有他
            if($data['order_type'] == 1){
                $user_order = Order::find()
                    ->where(['user_id'=>$this->user['id'],'order_type'=>1,'active_id'=>$data['active_id']])
                    ->orderBy(['created_time'=>SORT_DESC])
                    ->asArray()
                    ->one();
                if(!empty($user_order)){
                    $group = Group::find()->where(['id'=>$user_order['group_id']])->asArray()->one();
                    if($group['status'] == 2){//该团在有效期内
                        return $this->renderJson([],'不能重复参与当前团',ConstantService::$response_fail);
                    }
                }
            }

            $address = Address::find()->where(['id'=>$data['address_id']])->asArray()->one();
            if(empty($address)){
                return $this->renderJson([],'收货地址错误',ConstantService::$response_fail);
            }
            //收货地址
            $data['province'] = $address['province'];
            $data['city'] = $address['city'];
            $data['county'] = $address['area'];
            $data['address'] = $address['district'];
            $data['addressee_name'] = $address['name'];
            $data['addressee_phone'] = $address['mobile'];

            $data['user_id'] = $this->user['id'];
            $data['order_no'] = CommonService::createOrderNo();
            $data['created_time'] = time();
            $data['defaults_time'] = time()+ 60 * 60 * 24 * 15;
            $data['type_status'] = ConstantService::$order_status['PAY_WAIT'];
            $data['order_money'] = $data['goods_price'] + $data['freight'];
            $data['freight'] = sprintf("%.2f",$data['freight']);
            //直接存订单
            $order_model = new Order();
            $order_model->setAttributes($data);
            if($order_model->save()){
                $order_id = \Yii::$app->db->getLastInsertID();
                // @todo 目前是在支付成功的时候减掉库存,后期有化应该是生成订单时锁定库存
//                    $this->_reduceStock($data['goods_attr_id']);
                return $this->renderJson($order_id,'订单添加成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'订单添加失败',ConstantService::$response_fail);
//
//            //这里需要区分是单独购买还是拼团
//            $order_model = new Order();
//            if($data['type'] == 2){
//                //单独购买
//                $order_model->setAttributes($data);
//                if($order_model->save()){
//                    $order_id = \Yii::$app->db->getLastInsertID();
//                    // @todo 目前是在支付成功的时候减掉库存,后期有化应该是生成订单时锁定库存
//                    $this->_reduceStock($data['goods_attr_id']);
//                    return $this->renderJson($order_id,'订单添加成功',ConstantService::$response_success);
//                }
//                return $this->renderJson([],'订单添加失败',ConstantService::$response_fail);
//            }elseif ($data['type'] == 1) {
//                //团购 需要判断当前商品的团是否成团,如果成团则生成一个新团,伟成团则直接加进去
//                $active_id = $data['active_id'];
//                $current_group = Group::find()->where(['active_id' => $active_id])->orderBy(['id' => SORT_ASC])->one();
//                $surplus = $current_group['group_num'] - $current_group['current_group_num'];
//                if (!$surplus) {
//                    //需要新增新团
//                    $group_model = new Group();
//                    $active = Activity::findOne(['id' => $data['active_id']]);
//                    $group_row['launch_id'] = $this->user['id'];
//                    $group_row['active_id'] = $data['active_id'];
//                    $group_row['goods_id'] = $data['goods_id'];
//                    $group_row['shop_id'] = $data['shop_id'];
//                    $group_row['group_num'] = $active['activity_num'];
//                    $group_row['status'] = 2; //在有效期内
//                    $group_row['current_group_num'] = 1;
//                    $group_row['create_time'] = time();
//                    $group_row['update_time'] = time();
//                    $group_row['expire_time'] = time() + 60 * 60 * 24;
//                    $group_model->setAttributes($group_row);
//                    if (!($group_model->save())) {
//                        return $this->renderJson([], '成团表添加失败', ConstantService::$response_fail);
//                    }
//                    $date['group_id'] = \Yii::$app->db->getLastInsertID();
//                    //入订单表
//                    $order_model->setAttributes($date);
//                    if ($order_model->save()) {
//                        $order_id = \Yii::$app->db->getLastInsertID();
////                        // @todo 目前是在支付成功的时候减掉库存,后期有化应该是生成订单时锁定库存
////                          $this->_reduceStock($data['goods_attr_id']);
//                        return $this->renderJson($order_id, '订单添加成功', ConstantService::$response_success);
//                    }
//                    return $this->renderJson([], '订单添加失败', ConstantService::$response_fail);
//                } else {
                    //往之前团里面加
//                    $data['group_id'] = $current_group['id'];
//                    $order_model->setAttributes($data);
//                    if (!($order_model->save())) {
//                        return $this->renderJson([], '订单添加失败', ConstantService::$response_fail);
//                    }
//                    //修改成团数量表
//                    if ($surplus) {
//                        $current_group->current_group_num = $current_group['current_group_num'] + 1;
//                        $current_group->update_time = time();
//                        if ($current_group->save()) {
//                            $order_id = \Yii::$app->db->getLastInsertID();
//                            // @todo 目前是在支付成功的时候减掉库存,后期有化应该是生成订单时锁定库存
////                            $this->_reduceStock($data['goods_attr_id']);
//                            return $this->renderJson($order_id, '订单添加成功', ConstantService::$response_success);
//                        }
//                    }
//                    return $this->renderJson([], '订单添加失败', ConstantService::$response_fail);
//                }
//            }
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 修改订单
     *
     */
    public function actionUpdateOrder(){
        if($this->isPost()){
            $data = $this->post();
            if(empty($data['order_id']) || !isset($data['order_id'])){
                return $this->renderJson([],'订单id不能为空',ConstantService::$response_fail);
            }
            $msg = $this->_validation($data);

            if($msg!== true){
                return $this->renderJson([],$msg,ConstantService::$response_fail);
            }

            $order = Order::findOne(['id'=>$data['order_id']]);

            //加入redis存储库存
            $key = ConstantService::$redis_key.$data['goods_attr_id'];
            //判断key是否存在，不存在则新增
            $redis = RedisServer::initialization();
            $inventory = $redis->getRedis($key);

            $inventory = $inventory + $order['goods_num']-$data['goods_num'];
            if($inventory<0){
                return $this->renderJson([],'库存不足',ConstantService::$response_fail);
            }
            //设置值
            $redis->addRedis($key,$inventory);
            //拼数据
            $new_data = $this->_setData($data);
            if($new_data === false){
                return $this->renderJson([],'收货地址错误',ConstantService::$response_fail);
            }
            //直接存订单
            unset($new_data['order_id']);
            $order->setAttributes($new_data);
            if($order->save()){
                $order_id = \Yii::$app->db->getLastInsertID();
                // @todo 目前是在支付成功的时候减掉库存,后期有化应该是生成订单时锁定库存
//                    $this->_reduceStock($data['goods_attr_id']);
                return $this->renderJson($order_id,'订单修改成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'订单修改失败',ConstantService::$response_fail);
//


        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);

    }

    private function _setData($data){
        $address = Address::find()->where(['id'=>$data['address_id']])->asArray()->one();
        if(empty($address)){
            return false;
        }
        //收货地址
        $data['province'] = $address['province'];
        $data['city'] = $address['city'];
        $data['county'] = $address['area'];
        $data['address'] = $address['district'];
        $data['addressee_name'] = $address['name'];
        $data['addressee_phone'] = $address['mobile'];

        $data['user_id'] = $this->user['id'];
        $data['order_no'] = CommonService::createOrderNo();
        $data['created_time'] = time();
        $data['is_apply_after_sale'] = 0;
        $data['defaults_time'] = time()+ 60 * 60 * 24 * 15;
        $data['type_status'] = ConstantService::$order_status['PAY_WAIT'];
        $data['order_money'] = $data['goods_price'] + $data['freight'];
        $data['freight'] = sprintf("%.2f",$data['freight']);
        return $data;
    }


    /**
     * 添加订单验证
     * @param $data
     * @return string
     */
    private function _validation($data){
        if(empty($data['goods_id'])){
            return '商品id不能为空';
        }
        if(empty($data['goods_price'])){
            return '订单金额不能为空';
        }
        if(empty($data['goods_num'])){
            return '商品数量不能为空';
        }
        if(empty($data['shop_id'])){
            return '店铺id不能为空';
        }
        if(empty($data['active_id'])){
            return '活动id不能为空';
        }
        if(empty($data['goods_attr_id'])){
            return '商品属性id不能为空';
        }
        if(empty($data['address_id'])){
            return '收货地址不能为空';
        }
        if(empty($data['order_type'])){
            return '购买类型不能为空';
        }
        $order_modey = ActiveAttr::findOne(['id'=>$data['goods_attr_id']]);
        if($data['order_type'] == 1){
            $current_money = $data['goods_num'] * $order_modey['collage_price'];
            //团购
            if( $current_money != $data['goods_price']){
                return '订单金额与实际金额不符';
            }
        }else{
            //单独购买
            if($data['goods_num']*$order_modey['one_price'] != $data['goods_price']){
                return '订单金额与实际金额不符';
            }
        }

        return true;
    }

    /**
     * 获取用户订单
     */
    public function actionGetOrder(){
        if($this->isGet()){
            $status = $this->get('status',10);
            $user_id = $this->user['id'];
            $page = intval($this->get('page'));
            $page = ( $page > 0 )? $page : 1;

            $order_query = Order::find();
            $order_query->andWhere(['user_id'=>$user_id]);
            $order_query->andWhere(['is_delete'=>0]);
            switch ($status){
                //代付款 0
                case 0:
                    $order_query->andWhere(['order_status'=>ConstantService::$order_status['PAY_WAIT']]);
                    break;
                //待发货  1
                case 1:
                    $order_query->andWhere(['order_status'=>ConstantService::$order_status['WAIT_DELIVER']]);
                    break;
                //待收货 3
                case 3:
                    $order_query->andWhere(['order_status'=>ConstantService::$order_status['WAIT_RECEIPT']]);
                    break;
                //已完成 5
                case 5:
                    $order_query->andWhere(['>=','order_status',ConstantService::$order_status['SUCCESS']]);
                    $order_query->andWhere(['<=','order_status',ConstantService::$order_status['CLOSED']]);
                    break;
                //全部
                default:
                    break;
            }

            $offset = ($page - 1) * $this->page_size;

            $lists = $order_query
                ->select(['id','goods_id','shop_id','pay_status','order_status','order_type','transport_no',
                    'order_money','goods_price','freight','goods_num','user_id','active_id',
                    'goods_attr_id','created_time','is_apply_after_sale'])
                ->orderBy(['created_time' =>SORT_DESC ])
                ->offset( $offset )
                ->limit( $this->page_size )
                ->asArray()
                ->all();

            //查询商品活动信息
            $new_actives = [];
            $new_goods_attr = [];
            $attributes = [];
            $newshop = [];
            if(!empty($lists)){
                $active_id = array_column($lists,'active_id');
                if(!empty($active_id)){
                    $actives = Active::find()
                        ->select(['active_name','id as active_id'])
                        ->where(['id'=>$active_id])
                        ->asArray()
                        ->all();
                    foreach ($actives as $value){
                        $lenth = mb_strlen($value['active_name']);
                        if($lenth > 26){
                            $new_actives[$value['active_id']] = mb_substr($value['active_name'],0,26).'...';
                        } else {
                            $new_actives[$value['active_id']] = $value['active_name'];
                        }
                    }
                    unset($value);
                }
                $goods_attrs_ids = array_column($lists,'goods_attr_id');
                $goods_attrs = ActiveAttr::find()
                    ->where(['id'=>$goods_attrs_ids])
                    ->asArray()
                    ->all();
                foreach ($goods_attrs as $goods_attr){
                    $goods_attr['attr_img'] = GlobalUrlService::buildCdnUrl($goods_attr['attr_img']);
                    $new_goods_attr[$goods_attr['id']] = $goods_attr;
                }
                unset($goods_attr);
                //获取属性值
                $attributes = GoodsService::getCurrentArrt($goods_attrs_ids);

                $shopid  = array_column($lists,'shop_id');
                $shopdata = Shop::find()->select('id,shop_name,shop_logo')->where(['id'=>$shopid])->asArray()->all();

                foreach ($shopdata as $val){
                    $val['shop_logo'] = GlobalUrlService::buildCdnUrl($val['shop_logo']);
                    $newshop[$val['id']] = $val;
                }
            }
            foreach ($lists as &$list){
                $list['shop'] = '';
                if(!empty($newshop)){
                    $list['shop'] = $newshop[$list['shop_id']];
                }

                $list['status'] = CommonService::getOrderStatus($list['order_status']);
                //活动名称
                $list['active'] = [];
                if(isset($new_actives[$list['active_id']]) && !empty($new_actives[$list['active_id']])){
                    $list['active'] = $new_actives[$list['active_id']];
                }
                //活动属性
                $list['goods_attr'] = [];
                if(isset($new_goods_attr[$list['goods_attr_id']]) && !empty($new_goods_attr[$list['goods_attr_id']])){
                    $list['goods_attr'] = $new_goods_attr[$list['goods_attr_id']];
                }
                //sku
                $list['sku'] = '';
                if(isset($attributes[$list['goods_attr_id']]) && !empty($attributes[$list['goods_attr_id']])){
                    $list['sku'] = $attributes[$list['goods_attr_id']];
                }
                //这里需要获取未支付的订单剩余支付时间  秒数直接取00 防止最后几秒超时
                $list['minute'] = 0;
                $list['hours'] = 0;
                if($list['order_status'] == ConstantService::$order_status['PAY_WAIT']){
                    $over_time = time() - $list['created_time'];
                    $minute = floor(($over_time)/60);
                    $list['minute'] = 15 - ($minute<=0 ? 1:$minute);
                    $list['second'] = floor($over_time%60);

                }
                $list['order_status_show'] = CommonService::getOrderStatus($list['order_status']);
            }
            return $this->renderJson($lists,'查询成功',ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }
    /**
     * 取消订单
     */
    public function actionCancelOrder(){
        if($this->isGet()){
            $order_id = $this->get('order_id');
            $user_id = $this->user['id'];
            $order = Order::findOne(['id'=>$order_id,'user_id'=>$user_id]);
            $type = 0;
            //未支付的订单和支付过的订单点击取消状态不一样
            if($order['order_status'] == ConstantService::$order_status['PAY_WAIT']){
                $status = ConstantService::$order_status['CLOSED'];//关闭6
            }elseif ($order['order_status'] == ConstantService::$order_status['WAIT_DELIVER']){
                $type = 1;
                $order->refund_time = time();
                $status = ConstantService::$order_status['RETURNED_PURCHASE']; //退款中4
            }
            if($order){
                $order->order_status = $status;
                if($order->save()){
                    return $this->renderJson($type,'操作成功',ConstantService::$response_success);
                }
                return $this->renderJson([],'操作失败',ConstantService::$response_fail);
            }
            return $this->renderJson([],'该订单不存在',ConstantService::$response_fail);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 延长收货
     */
    public function actionExtendOrder(){
        if($this->isAjax()){

            $order_id = $this->get('id');
            $user_id = $this->user['id'];
            $order = Order::findOne(['id'=>$order_id,'user_id'=>$user_id]);
            if(!$order){
                return $this->renderJson([],'订单不存在',ConstantService::$response_fail);
            }
            $extend_time =60*60*24*3;//3天
            $time = time()-$order['defaults_time'];
            if($time>$extend_time){
                //还未到可以延长收货的时间
                return $this->renderJson([],'默认到期确认收货时间为3天后才允许延长收货',ConstantService::$response_fail);
            }
            $order->defaults_time = $order['defaults_time']+$extend_time;
            if($order->save()){
                return $this->renderJson([],'收货时间已经延长3天',ConstantService::$response_success);
            }
            return $this->renderJson([],'延长收货时间失败',ConstantService::$response_fail);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);

    }

    /**
     * 查看运单号
     */
    public function actionGetTransportNo(){
        if($this->isGet()){
            $order_id = $this->get('order_id');
            $user_id = $this->user['id'];
            $order = Order::find()->where(['id'=>$order_id,'user_id'=>$user_id])->asArray()->one();
//            $exp = Express::find()->where(['code'=>$order['express']])->asArray()->one();
            if($order){
                return $this->renderJson($order,'操作成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'该订单不存在',ConstantService::$response_fail);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 确认订单
     */
    public function actionConfirmOrder(){
        if($this->isPost()){
            $order_id = $this->post('order_id');
            $user_id = $this->user['id'];
            $order = Order::findOne(['user_id'=>$user_id,'id'=>$order_id]);
            $status = ConstantService::$order_status['SUCCESS'];
            if($order){
                $order->order_status = $status;
                $order->complete_time = time();

                if($order->save()){
                    //添加商户余额
                    $shop = Shop::findOne(['id' => $order['shop_id']]);
                    //商户余额
                    $money = sprintf("%.2f",$shop['shop_money']) + sprintf("%.2f",$order['order_money']);

                    $before_money = MoneyChange::find()
                        ->where(['shop_id'=>$order['shop_id']])
                        ->orderBy(['id'=>SORT_DESC])
                        ->one();
                    $before_money = !empty($before_money) ? $before_money['after_money'] :'0.00';
                    $change_model = new MoneyChange();
                    $data['money'] = sprintf("%.2f",$order['order_money']);
                    $data['after_money'] = sprintf("%.2f",$money);
                    $data['before_money'] = sprintf("%.2f",$before_money);
                    $data['shop_id'] = $order['shop_id'];
                    $data['remark'] = '订单流入';
                    $data['type'] = 0;
                    $data['create_time'] = time();
                    $change_model->setAttributes($data);
                    $change_model->save();
                    $shop->shop_money = sprintf("%.2f",$money);
                    $shop->save();
                    //添加销量 goods_attr_id
                    $current_goods_attr = ActiveAttr::findOne(['id'=>$order['goods_attr_id']]);
                    $current_goods_attr->sales_volume = $current_goods_attr['sales_volume']+1;
                    $current_goods_attr->save();

                    return $this->renderJson([],'操作成功',ConstantService::$response_success);
                }
                return $this->renderJson([],'操作失败',ConstantService::$response_fail);
            }
            return $this->renderJson([],'该订单不存在',ConstantService::$response_fail);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 删除订单
     */
    public function actionDelOrder(){
        if($this->isGet()){
            $order_id = $this->get('order_id');
            $user_id = $this->user['id'];
            $order = Order::findOne(['id'=>$order_id,'user_id'=>$user_id]);
            if($order){
                $order->is_delete = 1;
                if($order->save()){
                    return $this->renderJson([],'删除成功',ConstantService::$response_success);
                }
                return $this->renderJson([],'删除失败',ConstantService::$response_fail);

            }
            return $this->renderJson([],'该订单不存在',ConstantService::$response_fail);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 获取商家联系方式
     * @return array|null|\yii\db\ActiveRecord
     */
    public function actionGetShopPhone(){
        $shop_id = $this->get('shop_id');
        $data = Shop::find()->select('join_phone_two,admin_phone,shop_name')->where(['id'=>$shop_id,'status'=>1])->asArray()->one();

        if($data){
            return $this->renderJson($data,'操作成功',ConstantService::$response_success);
        } else {
            return $this->renderJson('','该商家不存在或已停用',ConstantService::$response_fail);
        }

    }

    /**
     * 获取拼团用户信息
     */
    public function actionGetgroupInfo(){
        $oid = $this->get('order_id');
        $group = Order::find()->select('active_id as aid,user_id,order_type,group_id,goods_num,goods_price,goods_attr_id')->where(['id'=>$oid])->asArray()->one();
        $data['aid'] = $group['aid'];
        $active = Active::find()->select('goods_img,active_name')->where(['id'=>$group['aid']])->asArray()->one();
        $data['goods_img'] = GlobalUrlService::buildCdnUrl($active['goods_img']);
        $data['active_name'] = $active['active_name'];
        $lenth = mb_strlen($active['active_name']);
        if($lenth > 26){
            $data['active_name'] = mb_substr($active['active_name'],0,26).'...';
        }
        $attr_value = GoodsService::getCurrentArrt([$group['goods_attr_id']]);
        if(isset($attr_value) && !empty($attr_value)){
            $data['attr_value'] = array_values($attr_value);
        }
        $data['goods_price'] = $group['goods_price'];
        $data['goods_num'] = $group['goods_num'];
        if ($group['order_type'] == 1) {
            $groupdata = Group::find()->select('create_time,complete_time,expire_time,group_num,current_group_num')->where(['id' => $group['group_id']])->asArray()->one();
            $num = $groupdata['group_num'] - $groupdata['current_group_num'];
            if ($group) {
                $user = Order::find()->select('user_id')->where(['group_id' => $group['group_id']])->asArray()->all();
                $user_id = array_column($user, 'user_id');

                $userdata = User::find()->select('nickname,avatarurl')->andwhere(['in','id',$user_id])->asArray()->all();
                foreach ($userdata as &$val) {
                    $val['nickname'] = base64_decode($val['nickname']);
                    $val['avatarurl'] = GlobalUrlService::buildCdnUrl($val['avatarurl']);
                }
                $data['groupdata'] = $num;
                $data['userdata'] = $userdata;
                $data['order_type'] = $group['order_type'];

                if($groupdata['complete_time']){
                    $data['time_type'] = 1;
                    $data['re_time'] = $groupdata['complete_time']-$groupdata['create_time'];
                } else {
                    $data['time_type'] = 0;
                    $data['re_time'] = $groupdata['expire_time'];
                }
                return $this->renderJson($data, '', ConstantService::$response_success);

            }
            return $this->renderJson('', '没有数据', ConstantService::$response_fail);
        }else {
            $userdata = User::find()->select('nickname,avatarurl')->where(['id' => $group['user_id']])->asArray()->one();
            $newuser['nickname'] = base64_decode($userdata['nickname']);
            if ($userdata['avatarurl']) {
                $newuser['avatarurl'] = GlobalUrlService::buildCdnUrl($userdata['avatarurl']);
            }
            $data['groupdata'] = 0;
            $data['userdata'][0] = $newuser;
            $data['order_type'] = $group['order_type'];

            return $this->renderJson($data, '', ConstantService::$response_success);
        }
    }

    /**
     * 获取未支付订单剩余时间
     */
    public function actionGetOverdue(){

        $order_id = $this->get('id');
        $order_model = Order::find();
        $order_model->andWhere(['id'=>$order_id]);
        $order_model->andWhere(['pay_status'=>ConstantService::$pay_status['WAIT_PAY']]);
        $order_model->andWhere(['is_delete'=>0]);

        $order = $order_model->asArray()->one();
        if(empty($order)){
            return $this->renderJson([],'该订单不存在',ConstantService::$response_fail);
        }
        $over_time = time() - $order['created_time'];
        $time = 15*60;
        if($over_time >= $time){
            return $this->renderJson([],'该订单已过期',ConstantService::$response_fail);
        }

//        $hours = floor($over_time/3600);
//        $minute = floor(($over_time-$hours*60*60)/60);
        $minute = floor($over_time/60);  //有问题
        $minute = $minute<=0 ? 1:$minute;
        $second = floor($over_time%60);

        $hours = 0;
        return $this->renderJson(['hours'=>$hours,'minute'=>$minute,'second'=>$second],'获取成功',ConstantService::$response_success);
    }

    /**
     * 订单详情
     */
    public function actionGetOrderInfo(){
        $id = $this->get('id');
        $data = Order::find()->where(['id'=>$id])->asArray()->one();

        $coms = Complaint::find()->where(['user_id'=>$this->user['id'],'order_id'=>$id])->asArray()->one();
        if($coms){
            $data['is_complaint'] = 1;
            $data['feedback_id'] = $coms['id'];
        } else {
            $data['is_complaint'] = 0;
            $data['feedback_id'] = '';
        }

        $data['status_order'] = CommonService::getOrderStatus($data['order_status']);
        //活动属性
        $act_attr = ActiveAttr::find()->where(['id'=>$data['goods_attr_id']])->asArray()->one();
        $act_attr['attr_img'] = GlobalUrlService::buildCdnUrl($act_attr['attr_img']);

        $attr_value = GoodsService::getCurrentArrt([$act_attr['id']]);
        $data['attr_img'] = $act_attr['attr_img'];
        if(isset($attr_value) && !empty($attr_value)) {
            $data['attr_value'] = array_values($attr_value);
        } else {
            $data['attr_value'] = '';
        }
        //活动名
        $activity = Active::find()->select('shop_id,id,goods_id,active_name,goods_id')->where(['id'=>$act_attr['active_id']])->asArray()->one();
        $shop = Shop::find()->select('id,shop_name,shop_logo,join_phone_two as shop_phone')->where(['id'=>$data['shop_id']])->asArray()->one();
        if($data['order_status'] == 3 || $data['order_status'] == 5){
            $exp = json_decode(LogisticsService::getOrderTracesByJson($data['express_code'],$data['transport_no']),true);

            if( isset($exp['Traces']) && !empty($exp['Traces'])){
                $explist = array_reverse($exp['Traces']);
                $data['exp_info'] = $explist[0];
            } else {
                $data['exp_info'] = array();
            }
        } else {
            $data['exp_info'] = array();
        }
        $shop['shop_name'] = $shop['shop_name'];
        $shop['shop_id'] = $shop['id'];
        $shop['shop_logo'] = GlobalUrlService::buildCdnUrl($shop['shop_logo']);
        $data['shop'] = $shop;
        $data['active_name'] = $activity['active_name'];
        $data['active_id'] = $activity['id'];
        $data['goods_id'] = $activity['goods_id'];
        if($data){
            return $this->renderJson($data,'',ConstantService::$response_success);
        }
        return $this->renderJson([],'该订单不存在',ConstantService::$response_fail);
    }

    /**
     * 获取物流信息
     */
    public function actionGetLogistics(){

        //根据订单id获取物流编号和商品单位
        $order_id = $this->get('id');
        if(empty($order_id)){
            return $this->renderJson([],'参数错误',ConstantService::$response_fail);
        }
        $order = Order::find()->where(['id'=>$order_id])->asArray()->one();
        $result = null;

        if($order['express_code'] == 'OTHER'){
            $result['EBusinessID'] = '';
            $result['LogisticCode'] = '';
            $result['State'] = '';
            $result['Success'] = '';
            $result['Traces'] = [];
        }else{
            $shippercode = $order['express_code'];//快递公司编号
            $logisticcode = $order['transport_no'];
            $result = LogisticsService::getOrderTracesByJson($shippercode,$logisticcode);
            $result = json_decode($result,true);
        }

        $act_attr = ActiveAttr::find()->where(['id'=>$order['goods_attr_id']])->asArray()->one();
        $order['image'] = GlobalUrlService::buildCdnUrl($act_attr['attr_img']);
        $result['order'] = $order;
        return $this->renderJson($result,'获取成功',ConstantService::$response_success);
    }
}